import React, { Component } from 'react'
import './List.css'
import PubSub from 'pubsub-js'

export default class List extends Component {
  state = {
    users: [],
    isFirst: true,
    isLoading: false,
    isErr: ''   // 错误信息
  }
  // 页面挂载完成后就发起订阅
  componentDidMount(){
    this.token = PubSub.subscribe('MY TOPIC', (_, usersObj)=>{
      // 根据收到的不同状态进行页面渲染
      this.setState(usersObj)
    });
  }

  // 页面卸载时，取消订阅
  componentWillUnmount(){
    PubSub.unsubscribe(this.token)
  }
  // 
  render() {
    // 首次进入，欢迎页
    if(this.state.isFirst){
      return (
        <div className="row">
          <h2>Welcome :)</h2>
        </div>
      )
    }
    // loading
    if(this.state.isLoading){
      return (
        <div className="row">
          <h2>Loading... </h2>
        </div>
      )
    }else if(this.state.isErr){
      // err
      return (
        <div className="row">
          <h2>Error :( </h2>
          <span>{this.state.isErr}</span>
        </div>
      )
    }else{
      // 展示用户列表
      const {users} = this.state
      return (
        <div className="row">
          {
            users.map(userObj=>{
              return (
                <div className="card" key={userObj.id}>
                  <a href={userObj.html_url} rel="noreferrer" target="_blank">
                    <img alt="avatar" src={userObj.avatar_url} style={{width: '100px'}}/>
                  </a>
                  <p className="card-text">{userObj.login}</p>
                </div>
              )
            })
          }
        </div>
      )
    }
  }
}
